package org.the.gsdo.server;

import java.util.List;
import java.util.UUID;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.the.gsdo.shared.FieldVerifier;
import org.the.gsdo.shared.User;

public class GreetingManagerBase {

	private final PropertyProvider propertyProvider;

	// unfortunately it is not possible to inject the PersistenceContext into the constructor
	// we could wrap it and a class PersistenceContextWrapper and inject this one into GreetingManager
	// via constructor
	// PersistenceContextWrapper would be Lazy(true), Component, Scope("request")
	@PersistenceContext
	private EntityManager em;

	// AOP needs this one
	public GreetingManagerBase() { this(null); }

	public GreetingManagerBase(PropertyProvider propertyProvider) {
		this.propertyProvider = propertyProvider;
	}

	protected String greetServerX(String input, String serverInfo, String userAgent)
		throws IllegalArgumentException {

		// now, let's hack away ...
		@SuppressWarnings("unchecked") // hey, we can use native queries
		List<User> users = em.createNativeQuery("select x_id, x_username from x_user where x_username = ?1", User.class)
			.setParameter(1, input)
			.getResultList();
		User user = (users.size() > 0 ? users.get(0) : null);
		String welcome = "Welcome";
		System.out.println("User = " + user);
		if (user != null) {
			welcome = "Welcome back";
		} else {
			user = new User();
			user.setId(UUID.randomUUID().toString());
			user.setUsername(input);
			em.persist(user);
		}

		// Verify that the input is valid.
		if (!FieldVerifier.isValidName(input)) {
			// If the input is not valid, throw an IllegalArgumentException back to
			// the client.
			throw new IllegalArgumentException(
					"Name must be at least 4 characters long");
		}

		// Escape data from the client to avoid cross-site script vulnerabilities.
		input = escapeHtml(input);
		userAgent = escapeHtml(userAgent);

		return "[" + this + "]"
				+ "<br />" + welcome + ", " + input
				+ "!<br><br>I am running " + serverInfo
				+ (userAgent != null ? ".<br><br>It looks like you are using:<br>" + userAgent : "")
				+ "<br /><br />Version: " + propertyProvider.getProperty(PropertyProvider.Key.VERSION);
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 *
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}

}
